﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RedeSocial.ViewModels;
using System.Web.UI.WebControls;
using RedeSocial.ViewModels.Interfaces;

namespace RedeSocial.Web
{
	public abstract class BaseMasterPage : System.Web.UI.MasterPage
	{
		#region properties...
		protected virtual IBaseViewModel ViewModel { get; set; }
		#endregion
		#region overrides...
		protected override void OnLoad(EventArgs e)
		{
			if (ViewModel == null)
				CreateViewModel();

			BindViewModel();

			if (!IsPostBack)
				BindLabels();

			if (IsPostBack && ViewModel != null)
			{
				ViewModel.Validate();
			}
			base.OnLoad(e);

		}
		#endregion
		#region methods...
		protected virtual bool ValidateViewModel(string propertyName)
		{
			if (ViewModel != null)
				return string.IsNullOrEmpty(ViewModel[propertyName]);
			else return false;
		}
		protected void CustomValidation(object source, ServerValidateEventArgs args)
		{
			CustomValidator cv = source as CustomValidator;
			if (cv == null || ViewModel == null || string.IsNullOrEmpty(cv.Attributes["ModelProperty"]))
			{
				args.IsValid = false;
				return;
			}
			args.IsValid = string.IsNullOrEmpty(ViewModel[cv.Attributes["ModelProperty"]]);
			if (!args.IsValid)
				cv.ErrorMessage = ViewModel[cv.Attributes["ModelProperty"]];
		}
		#endregion
		#region abstract methods...
		protected abstract void BindLabels();
		protected abstract void BindViewModel();
		protected abstract void CreateViewModel();
		#endregion
	}
}